package org.thunms.framework.core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.util.WebUtils;
import org.thunms.framework.utils.UtilSystemProperties;

public class ResourceListener implements ServletContextListener, ServletContextAttributeListener, HttpSessionListener, HttpSessionAttributeListener, HttpSessionActivationListener, HttpSessionBindingListener, ServletRequestListener, ServletRequestAttributeListener {
	private static final Logger logger = LoggerFactory.getLogger(ResourceListener.class);
	private Boolean refresh = true;
	private String basePath = null;

	@Override
	public void attributeAdded(ServletRequestAttributeEvent srae) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeRemoved(ServletRequestAttributeEvent srae) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeReplaced(ServletRequestAttributeEvent srae) {
		// TODO Auto-generated method stub

	}

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		// TODO Auto-generated method stub

	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		// TODO Auto-generated method stub

	}

	@Override
	public void valueBound(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub

	}

	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sessionWillPassivate(HttpSessionEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sessionDidActivate(HttpSessionEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeAdded(ServletContextAttributeEvent scab) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeRemoved(ServletContextAttributeEvent scab) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeReplaced(ServletContextAttributeEvent scab) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//refresh = UtilSystemProperties.getPropertyBoolean("thunms.refresh.resource.auto");
		refresh=true;
		if (refresh) {
			logger.debug("这这里解析配置文件");
			try {
				basePath = WebUtils.getRealPath(sce.getServletContext(), "/WEB-INF");

				logger.info("=======================开始释放jsp资源=============================");
				Resource[] rsjsp = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/**/**/views/**/*.jsp");
				for (Resource resource : rsjsp) {
					logger.debug("获取到的资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/views/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/views/").append(rp);
					logger.debug("动态分解到的资源目标路径======》》》" + toFilePath);
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
				}
				logger.info("=======================jsp资源释放完毕=============================");
				logger.info("=======================开始释放报表引擎资源=============================");
				Resource[] reports = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/**/**/reports/**/*.jrxml");
				for (Resource resource : reports) {
					logger.debug("获取到的资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/reports/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/reports/").append(rp);
					logger.debug("动态分解到的资源目标路径======》》》" + toFilePath);
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
				}
				logger.info("=======================报表资源释放完毕=============================");
				
				logger.info("=======================开始释放模板引擎资源=============================");
				Resource[] freemarkers = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/**/**/templates/**/*.html");
				for (Resource resource : freemarkers) {
					logger.debug("获取到的资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/templates/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/t/").append(rp);
					logger.debug("动态分解到的资源目标路径======》》》" + toFilePath);
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
				}
				logger.info("=======================模板引擎资源释放完毕=============================");


				logger.info("=======================开始释放css资源=============================");
				Resource[] rscss = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/**/**/resource/css/*.css");
				for (Resource resource : rscss) {
					logger.debug("获取到的资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/resource/css/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/css/").append(rp);
					//StringBuilder toFilePath=new StringBuilder(resource.getURL().getPath().replace("/resource/css/", "/").replace("/classes/org/thunms/", "/css/"));
					logger.debug("动态分解到的资源目标路径======》》》" + toFilePath);
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
				}
				//目录拷贝
				Resource[] rscssDirectory = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/resource/css/**/**.*");

				for (Resource resource : rscssDirectory) {
					if(resource.getFilename().lastIndexOf(".flt")==-1){
					logger.debug("获取到的资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/resource/css/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/css/").append(rp);

					//StringBuilder toFilePath=new StringBuilder(resource.getURL().getPath().replace("/resource/script/", "/").replace("/classes/org/thunms/", "/script/"));
					logger.debug("动态分解到的资源目标路径======》》》" + toFilePath);
					logger.debug("动态分解到的资源目标路径======》》》" + resource.getFilename());
					if(!"/".equals(toFilePath.substring(toFilePath.length()-1))){
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
					}
					}
					/*if(resource.getFile().isDirectory()){
						FileUtils.copyDirectory(resource.getFile(), new File(toFilePath.toString()));
					}*/
				}
				logger.info("=======================css资源释放完毕=============================");
				logger.info("=======================开始释放javaScript资源=============================");
				Resource[] rsscript = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/**/**/resource/script/*.js");
				for (Resource resource : rsscript) {
					logger.debug("获取到的资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/resource/script/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/script/").append(rp);

					//StringBuilder toFilePath=new StringBuilder(resource.getURL().getPath().replace("/resource/script/", "/").replace("/classes/org/thunms/", "/script/"));
					logger.debug("动态分解到的资源目标路径======》》》" + toFilePath);
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
				}
				//目录拷贝
				Resource[] rsscriptDirectory = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/resource/script/**/**.*");

				for (Resource resource : rsscriptDirectory) {
					if(resource.getFilename().lastIndexOf(".flt")==-1){
					logger.debug("获取到的资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/resource/script/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/script/").append(rp);

					//StringBuilder toFilePath=new StringBuilder(resource.getURL().getPath().replace("/resource/script/", "/").replace("/classes/org/thunms/", "/script/"));
					logger.debug("动态分解到的资源目标路径======》》》" + toFilePath);
					logger.debug("动态分解到的资源目标路径======》》》" + resource.getFilename());
					if(!"/".equals(toFilePath.substring(toFilePath.length()-1))){
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
					}
					}
					/*if(resource.getFile().isDirectory()){
						FileUtils.copyDirectory(resource.getFile(), new File(toFilePath.toString()));
					}*/
				}
				logger.info("=======================javaScript资源释放完毕=============================");
				logger.info("=======================开始释放图片资源=============================");
				//目录拷贝
				Resource[] rsimages = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/**/**/resource/images/**/**.*");

				for (Resource resource : rsimages) {
					if(resource.getFilename().lastIndexOf(".flt")==-1){
					logger.debug("获取到的资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/resource/images/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/images/").append(rp);
					//StringBuilder toFilePath=new StringBuilder(resource.getURL().getPath().replace("/resource/images/", "/").replace("/classes/org/thunms/", "/images/"));
					logger.debug("动态分解到的资源目标路径======》》》" + toFilePath);
					/*if(resource.getFile().isDirectory()){
						FileUtils.copyDirectory(resource.getFile(), new File(toFilePath.toString()));
					}*/
					if(!"/".equals(toFilePath.substring(toFilePath.length()-1))){
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
					}
					}
				}
				logger.info("=======================图片资源释放完成=============================");
				//释放静态资源.新增加纯静态的html文件的处理方式.
				logger.info("=======================开始释放纯静态的html资源=============================");
				//目录拷贝
				Resource[] rshtmls = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/**/**/static/**/**/**.*");

				for (Resource resource : rshtmls) {
					//排除掉模板文件
					if(resource.getFilename().lastIndexOf(".flt")==-1){
					logger.debug("获取到的纯静态的html资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/static/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/static/").append(rp);
					//StringBuilder toFilePath=new StringBuilder(resource.getURL().getPath().replace("/resource/images/", "/").replace("/classes/org/thunms/", "/images/"));
					logger.debug("动态分解纯静态的html资源目标路径======》》》" + toFilePath);
					/*if(resource.getFile().isDirectory()){
						FileUtils.copyDirectory(resource.getFile(), new File(toFilePath.toString()));
					}*/
					if(!"/".equals(toFilePath.substring(toFilePath.length()-1))){
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
					}
					}
				}
				logger.info("=======================纯静态的html资源释放完成=============================");
				//释放freemarker资源.新增加纯静态的html文件的处理方式.
				logger.info("=======================开始释放模板ftl资源=============================");
				//目录拷贝
				Resource[] rsftls = new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/org/thunms/resource/freemarker/**/**/**.ftl");

				for (Resource resource : rsftls) {
					//排除掉模板文件
					if(resource.getFilename().lastIndexOf(".flt")==-1){
					logger.debug("获取到的模板ftl资源路径======》》》" + resource.getURL().getPath());
					StringBuilder rp = new StringBuilder(resource.getURL().getPath().replace("/resource/freemarker/", "/"));
					rp.delete(0, rp.indexOf("/org/thunms/") + 12);
					StringBuilder toFilePath = new StringBuilder(basePath).append("/t/").append(rp);
					//StringBuilder toFilePath=new StringBuilder(resource.getURL().getPath().replace("/resource/images/", "/").replace("/classes/org/thunms/", "/images/"));
					logger.debug("动态分解模板ftl资源目标路径======》》》" + toFilePath);
					/*if(resource.getFile().isDirectory()){
						FileUtils.copyDirectory(resource.getFile(), new File(toFilePath.toString()));
					}*/
					
					FileUtils.copyInputStreamToFile(resource.getInputStream(), new File(toFilePath.toString()));
					}
				}
				logger.info("=======================释放模板ftl资源完成=============================");
			} catch (IOException e) {
				logger.error("系统资源初始化错误", e);
				System.exit(0);
			}
		}
		
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		/*if (this.refresh) {
			if (basePath != null) {
				try {
					FileUtils.deleteDirectory(new File(basePath + "/css"));
					FileUtils.deleteDirectory(new File(basePath + "/script"));
					FileUtils.deleteDirectory(new File(basePath + "/views"));
				} catch (IOException e) {
					logger.error("资源清理过程出现错误", e);
				}
			}
		}*/

	}
	
}
